const bcrypt = require('bcryptjs')
const { getUserInfo } = require('../service/user.service')
const { userFormateError ,
    userAlreadyExited ,
    userRegisterError,
    userDoesNotExist,
    userLoginErr,
    invalidPassword,
} = require('../constant/err.type')
// 验证注册数据格式
const userValidator = async (ctx, next) => {
    const { user_account, password } = ctx.request.body
    // 判空
    if (!user_account || !password) {
        console.error('用户名或密码为空',ctx.request.body)
        ctx.app.emit('error',userFormateError,ctx)
        return
    }

    await next()
}
// 验证注册用户是否存在
const verifyUser = async (ctx, next) => {
    const {user_account} = ctx.request.body
    try {
        const res = await getUserInfo({ user_account })
        console.log('111')
        if(res) {
            console.error('用户已经存在',{user_account})
            ctx.app.emit('error',userAlreadyExited,ctx)
            return
        }
    }catch (err) {
        console.error('数据库查询用户是否存在出错',err)
        ctx.app.emit('error',userRegisterError,ctx)
        return
    }
    await next()
}
// 注册密码加密
const crpytPassword = async (ctx, next) => {
    const {password} = ctx.request.body
    const salt = bcrypt.genSaltSync(10);
    const hash = bcrypt.hashSync(password,salt)
    ctx.request.body.password = hash
    await next()
}

// 登录判断用户是否存在 密码是否匹配
const verifyLogin = async (ctx,next) => {
    const {user_account,password} = ctx.request.body
    const res =  await getUserInfo({user_account})
    try {
        if(!res) {
            console.error('用户名不存在',{user_account})
            ctx.app.emit('error',userDoesNotExist,ctx)
            return
        }
    }catch (e) {
        console.error('登录判断用户是否存在出错',err)
        ctx.app.emit('error',userLoginErr,ctx)
        return
    }
    if(!bcrypt.compareSync(password,res.password)){
        ctx.app.emit('error',invalidPassword,ctx)
        return
    }
    await next()
}


module.exports = {
    userValidator,
    verifyUser,
    crpytPassword,
    verifyLogin
}